package action;

import Bean.UserBean;
import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * 是否为注册用户操作
 */
public class IsRegisterUserAction extends ActionSupport {
    public String isRegisterUser() throws Exception {

        boolean result = false;

        HttpServletRequest request = ServletActionContext.getRequest();
        request.setCharacterEncoding("utf-8");
        ServletInputStream inputStream = request.getInputStream();

        StringBuilder stringBuilder = new StringBuilder();

        int len = 0;
        byte[] bytesBuf = new byte[1024];
        while ((len=inputStream.read(bytesBuf)) != -1){
            stringBuilder.append(new String(bytesBuf, 0, len));
        }

        String s = stringBuilder.toString();

        Gson gson = new Gson();
        UserBean userBean = gson.fromJson(s, UserBean.class);


        System.out.println(userBean.toString());
        String telephone = userBean.getTelephone();
        String password = userBean.getPassword();
        String name = userBean.getName();
        System.out.println("userIsRegisterUser ==> "+userBean.toString());

        //1.导入驱动
        //2.加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //3.java连接数据库（需要：用户名、密码、端口号、url）   java------>mysql 建桥
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/wu_db?useSSL=false&serverTimezone=UTC", "root", "123456");
        //4.创建一个人：Sql
        String sql="SELECT * FROM user_tb WHERE telephone = '"+telephone+"'";
        //5.创建一辆车：Statement
        Statement statement = conn.createStatement();
        //6.人上车，发车，走桥。
        ResultSet resultSet = statement.executeQuery(sql);
        int count = 0;
        while (resultSet.next()){
            count = resultSet.getInt(1);
        }

        System.out.println("查询得到的行数："+count);
        if (count>0) {
            result = true;
        }
        //7.炸车
        statement.close();
        //8.炸桥
        conn.close();


        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(String.valueOf(result));
        System.out.println("result ==> "+String.valueOf(result));
        result = false;
        System.out.println("result ==> "+String.valueOf(result));
        writer.flush();
        return null;
    }

}
